"""
  Created by Amor on 2018-09-01
"""
from flask import jsonify, g
from werkzeug.exceptions import Forbidden

from app.libs.error_code import DeleteSuccess
from app.libs.redprint import Redprint
from app.libs.token_auth import auth
from app.models.base import db
from app.models.user import User

__author__ = '骆杨'


api = Redprint('user')


@api.route('/<int:uid>', methods=['GET'])
@auth.login_required
def get_user(uid):
    user = User.query.filter_by(id=uid).first_or_404()
    return jsonify(user)


@api.route('/<int:uid>', methods=['DELETE'])
@auth.login_required
def delete_user(uid):
    if uid != g.user.uid:
        raise Forbidden
    with db.auto_commit():
        user = User.query.filter_by(id=uid).first_or_404()
        user.delete()
    return DeleteSuccess()


@api.route('', methods=['GET'])
@auth.login_required
def get_user_list():
    user_list = User.query.all()
    return jsonify(user_list)
